package com.juzipi.thread.test.demo;

/**
 * @Author juzipi
 * @Date 2021/6/16 8:36
 * @Info
 */
public class UnsafeBank {

    public static void main(String[] args) {
        Account account = new Account("账户所有金额",10000.00);

        Bank bank = new Bank(account,10000);
        Bank bank1 = new Bank(account,3000);
        Thread thread = new Thread(bank,"张三");
        Thread thread1 = new Thread(bank1,"余秀丽");
        thread.start();
        thread1.start();

    }

}

class Account{

    String name;

    Double money;

    public Account(String name, Double money) {
        this.name = name;
        this.money = money;
    }

}

class Bank implements Runnable{

    Account account;//账户

    int quMoney;//要取得钱

    int nowMoney;//手里的钱

    @Override
    public void run() {

        //同步代码块，锁的对象是变化的量（就是公共资源）
        synchronized (account){
            if (account.money - quMoney < 0){
                System.out.println(Thread.currentThread().getName()+"取钱 钱不够啦");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"取了:: "+quMoney);
            account.money -= quMoney;//账户减钱
            nowMoney += quMoney;//手里的钱
            System.out.println(account.name+"  账户所剩余额: "+account.money+"    @@@@@@@@@@@@@@@@@@@");
            System.out.println(Thread.currentThread().getName()+"手里还有："+nowMoney+"    @@@@@@@@@@@@@@@@@@@");
        }

    }

    public Bank() {
    }

    public Bank(Account account, int quMoney) {

        this.account = account;
        this.quMoney = quMoney;
    }
}
